package com.zyg.cart.controller;

import com.alibaba.fastjson.JSON;
import com.zyg.cart.client.ManagerClient;
import com.zyg.cart.client.OrderClient;
import com.zyg.cart.entity.group.Cart;
import com.zyg.cart.service.CartService;
import com.zyg.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * ------------------------------
 * 功能：
 * 作者：WF
 * 微信：hbxfwf13590332912
 * 创建时间：2021/11/15-15:06
 * ------------------------------
 */
@Controller
@RequestMapping
public class CartController {
    @Autowired
    private ManagerClient managerClient;
    @Autowired
    private CartService cartService;
    @Autowired
    private OrderClient orderClient;
    //1. 根据sku的id查询sku商品
    @GetMapping("cart/manager/item/info/{id}")
    @ResponseBody
    public R info(@PathVariable("id") Long id){
        return managerClient.info(id);
    }

    //2. 添加购物车
    @GetMapping("cart/add/{itemId}/{num}")
    // @ResponseBody
    public String add(@PathVariable("itemId") Long itemId,@PathVariable("num") int num){  //itemId: sku商品id num: 购买数量
        //2.1 得到登录名
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        System.out.println("name = " + name);
        //2.2 添加到购物车
        cartService.addCart(name,itemId,num);

        return "redirect:/";
    }

    //3. 展示购物车列表
    @GetMapping({"/","/cart.html"})
    public String showCartList(Model model){
         //3.0 得到登录名
         String name = SecurityContextHolder.getContext().getAuthentication().getName();
         //3.1 查询出redis中所有购物车列表
         List<Cart> cartList = cartService.showCartList(name);
         //3.2 放购物车列表到model中
        model.addAttribute("cartList",cartList);
        return "cart";
    }

    //4. 得到购物车集合数据
    @GetMapping(value="/cart/cartList/{name}")
    @ResponseBody
    public String cartList(@PathVariable String name){        //name：登录名
        return JSON.toJSONString(cartService.showCartList(name));
    }


    @GetMapping("hello")
    public String hello(){
        return orderClient.hello();
    }
}
